#include "dbalbum.h"
#include "connection.h"
#include <QSqlQuery>
#include <QString>
#include <QSqlError>
#include <QVariant>
#include <QSqlRecord>
#include <QDebug>

DbAlbum::DbAlbum()
{
}

bool DbAlbum::create(QList<DtAlbum *> &album)
{
    if(album.isEmpty())
        return true;
    Connection *con = Connection::getInstance();
//    WProgressBar * progress = WProgressBar::getInstance();
//    progress->setMaximumStep(album.size());
//    progress->setText("Inserting album");
    if(con->isConnected())
    {
        const int MaxBoucle = 999 / 4;
        QSqlQuery query;

        int i = 0;
        int nbInsert = 0;
        QList<DtAlbum *>::ConstIterator itG = album.constBegin();
        QList<DtAlbum *>::ConstIterator itL = album.constBegin();
        while(itG != album.constEnd())
        {
            i = 0;
            QString cmd = "INSERT INTO Album (name, year, cover, heart)";
            for(; itG != album.constEnd() && i < MaxBoucle; itG ++)
            {
                if((*itG)->getId() == -1)
                {
                    if(i == 0)
                        cmd += " SELECT";
                    else
                        cmd += " UNION ALL SELECT";
                    QString n;
                    n.setNum(i);
                    cmd += " :n" + n + ", :y" + n + ", :c" + n + ", :h" + n;
                    i ++;
                }
            }
            if(i == 0)
                return true;
            nbInsert += i;
            if(!query.prepare(cmd))
            {
                qDebug() << query.lastQuery() << query.lastError().text();
                return false;
            }

            i = 0;
            for(; itL != album.constEnd() && i < MaxBoucle; itL ++)
            {
                if((*itL)->getId() == -1)
                {
                    QString n;
                    n.setNum(i);
                    query.bindValue(":n" + n, (*itL)->getName());
                    query.bindValue(":y" + n, (*itL)->getYear());
                    query.bindValue(":c" + n, (*itL)->getCovers());
                    query.bindValue(":h" + n, (*itL)->getHeart());
                    i ++;
                }
            }
            if(!query.exec())
            {
                //            qWarning() << "Album " << cmd;
                qWarning() << "DbAlbum" <<query.lastError().text();
            }
            query.finish();
        }
        QSqlQuery q("select max(id) as id from album");
        if(q.next())
        {
            int lastId = q.value(0).toInt();
            int beforeId = lastId + 1 - nbInsert;
            for(QList<DtAlbum *>::iterator itId = album.begin();
                itId != album.end(); itId ++)
            {
                if((*itId)->getId() == -1)
                {
                    (*itId)->setId(beforeId);
                    beforeId++;
                }
            }
        }
//        progress->stop();
        return true;
    }
    return false;
}

bool DbAlbum::destroy(const QList<DtAlbum *> & album)
{
    if(album.isEmpty())
        return true;

    Connection *con = Connection::getInstance();
    if(con->isConnected())
    {
        QString requete = "DELETE FROM Album WHERE id = ?";
        for(int i = 1; i < album.size(); i++)
        {
            requete += " or id = ?";
        }
        QSqlQuery query;
        query.prepare(requete);
        int i = 0;
        for(QList<DtAlbum *>::ConstIterator it = album.constBegin();
            it != album.constEnd(); it++)
        {
            query.bindValue(i, (*it)->getId());
            i++;
        }

        if(!query.exec())
        {
            qWarning() << dbAlbumStr << dbAlbumDestroy
                       << query.lastError().text();
            return false;
        }
        return true;
    }
    return false;
}

bool DbAlbum::update(const QList<DtAlbum *> & album)
{
    if(album.isEmpty())
        return true;

//    Connection *con = Connection::getInstance();
//    if(con->isConnected())
//    {
//        QSqlQuery query;
//        query.prepare("UPDATE FROM Album WHERE id = :id set name = :name,"
//                      " year = :year, covers = :covers, heart = :heart,"
//                      );
//        query.bindValue(":id", album.getId());
//        query.bindValue(":name", album.getName());
//        query.bindValue(":year", album.getYear().toString("dd/MM/yyyy"));
//        query.bindValue(":covers", album.getCovers());
//        query.bindValue(":heart", album.getHeart());
//        if(!query.exec())
//        {
//            Journal::print(Journal::Err, dbAlbumStr, dbAlbumUpdate,
//                           query.lastError().text());
//            return false;
//        }
//        return true;
//    }
//    return false;
    return true;
}

bool DbAlbum::getAll(Collection &collection)
{
    Connection *con = Connection::getInstance();
    if(con->isConnected())
    {
        QString requete = "SELECT id, name, year, cover, heart FROM Album";
        QSqlQuery query(requete);
        QSqlRecord rec = query.record();
        int idCol = rec.indexOf("id");
        int nameCol = rec.indexOf("name");
        int yearCol = rec.indexOf("year");
        int coverCol = rec.indexOf("cover");
        int heartCol = rec.indexOf("heart");
        while(query.next())
        {
            DtAlbum *alb = new DtAlbum(query.value(nameCol).toString(),
                                       query.value(yearCol).toInt(),
                                       query.value(idCol).toInt(),
                                       query.value(coverCol).toString(),
                                       query.value(heartCol).toBool());
            /* Todo See if is a similar album but with differents id what to to
             *??? */
            if(!collection.addAlbum(alb))
                delete alb;
        }
        return true;
    }   
    return false;
}

bool DbAlbum::setHeart(const DtAlbum &album)
{
    Connection *con = Connection::getInstance();
    if(con->isConnected())
    {
        QString requete = "UPDATE album SET heart = :heart WHERE id = :id";
        QSqlQuery query;
        query.prepare(requete);
        query.bindValue(":heart", album.getHeart() ? 1 : 0);
        query.bindValue(":id", album.getId());
        if(!query.exec())
        {
            qWarning() << dbAlbumStr << query.lastQuery()
                       << query.lastError().text();
            return false;
        }
        return true;
    }
    return false;
}
